package com.neusoft.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.neusoft.base.BaseServiceImpl;
import com.neusoft.config.Pagination;
import com.neusoft.mapper.CategoryMapper;
import com.neusoft.mapper.ItemMapper;
import com.neusoft.model.CategorySearch;
import com.neusoft.po.Category;
import com.neusoft.po.Item;
import com.neusoft.service.CategoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 商品分类服务实现
 *
 * @author Lucifer
 * @since 2021/5/15 23:26
 */
@Service
public class CategoryServiceImpl extends BaseServiceImpl<Category> implements CategoryService {


    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private ItemMapper itemMapper;

    @Override
    public BaseMapper<Category> getBaseDao() {
        return categoryMapper;
    }

    @Override
    public List<Category> all() {
        return categoryMapper.all();
    }

    @Override
    @Pagination
    public Object page(CategorySearch pageSearch) {
        QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(pageSearch.getName())) {
            categoryQueryWrapper.like("name", pageSearch.getName());
        }
        return categoryMapper.selectList(categoryQueryWrapper);
    }

    @Override
    public Integer save(Category entity) {
        Integer id = entity.getId();
        if (null == id) {
            insert(entity);
            id = entity.getId();
        } else {
            updateById(entity);
        }
        return id;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer delete(Integer[] ids) {
        for (Integer id : ids) {
            Integer count = itemMapper.selectCount(new QueryWrapper<Item>().eq("category_id", id));
            if (count != 0) {
                Category category = categoryMapper.selectById(id);
                throw new RuntimeException("商品分类[" + category.getName() + "]下有未删除的商品是否强制删除？");
            } else {
                categoryMapper.deleteById(id);
            }
        }
        return ids.length;
    }

    @Override
    public void check(Integer[] ids) {
        StringBuilder sb = new StringBuilder("商品分类");
        for (Integer id : ids) {
            Integer count = itemMapper.selectCount(new QueryWrapper<Item>().eq("category_id", id));
            if (count != 0) {
                Category category = categoryMapper.selectById(id);
                sb.append("[" + category.getName() + "]").append("、");
            }
        }
        if (sb.length() > 4) {
            sb.deleteCharAt(sb.length() - 1).append("下有商品，是否强制删除分类？");
            throw new RuntimeException(sb.toString());
        }
    }
}
